## transfer TCGA VCF 4.1 to file in bed format: chr + start + end + strand + methylation value + number of CT reads..
## author: Yaping Liu  lyping1986@gmail.com


my $input_file_name = $ARGV[0];
#my $sample_name = $ARGV[1];
my $search_pattern = $ARGV[1];

my $use_age = "USAGE: perl vcf2cpg_wig_plus_file.pl input_file_name search_pattern";
if($input_file_name eq ""){
	print "$use_age\n";
	exit(1);
}

my $cpg_name_output = $input_file_name.".$search_pattern.bed";
open(OUT,">$cpg_name_output") or die;

#my $head_line = "track type=wiggle_0 name=".$sample_name." description=".$sample_name;
#variableStep chrom=chr19 span=150"
#print OUT "$head_line\n";

open(FH,"<$input_file_name") or die;
my @in=<FH>;
chomp(@in);
close(FH);

foreach my $line(@in){
	next if $line =~ /^#/;
	my @splitin = split "\t", $line;
	next unless $splitin[6] eq "PASS";
	if($splitin[7] =~ /$search_pattern/){
		my $num_c;
		my $num_t;
		my $strand=".";
		if($splitin[7] =~ /Cm=(\d+)/){
			$num_c = $1;	
		}
		if($splitin[7] =~ /Cu=(\d+)/){	
			$num_t = $1;
		}
		if($splitin[7] =~ /Strand=([+|-])/){
			$strand = $1;
		}
		my $methy = 'NaN';
		if($num_c + $num_t != 0){
			$methy = $num_c/($num_c + $num_t);
			$methy = sprintf("%.2f",100*$methy);
		}
		my $chr = $splitin[0];
		my $start = $splitin[1]-1;
		my $end = $splitin[1];
		 my $reads_num = $num_c + $num_t;
		my $out_line = "$chr\t$start\t$end\t$strand\t$methy\t$reads_num";
		print OUT "$out_line\n";
	}
}
close(OUT);


